package com.woldier.filesystem.interceptor;


import com.woldier.base.utils.UserHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String username   =  request.getHeader("username");
        if(StringUtils.isEmpty(username)) {
            /*为空说明未授权，由于网管做了登录校验到这里的都是有值的*/
            //response.setStatus(401);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"请求头不存在username字段");
            return  false;
        }
        UserHolder.setUser(username);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
